package com.example.kafka.service;

import com.example.kafka.dto.UserQueryLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Random;

/**
 * 模拟查询，实现日志的发送
 * ELK示例
 *
 * @author wkj
 */
@Slf4j
@Service
public class KafkaLogService {

    private final KafkaTemplate<String, String> kafkaTemplate;

    public KafkaLogService(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    /**
     * 发送用户查询日志
     *
     * @param userLog 用户查询日志
     */
    public void sendUserQueryLog(UserQueryLog userLog) {
        try {
            kafkaTemplate.send("user-query-logs", userLog.toString());
            log.info("Sent log to Kafka: {}", userLog);
        } catch (Exception e) {
            log.error("Failed to send log to Kafka: {}", log, e);
        }
    }

    private final Random random = new Random();

    /**
     * 查询用户信息
     *
     * @param userId 用户ID
     * @param query  查询条件
     * @return
     */
    public String queryUserInfo(String userId, String query) {
        // 模拟查询处理
        boolean success = random.nextBoolean();
        String result;

        if (success) {
            result = "用户信息，用户ID： " + userId + "，用户条件：" + query;
        } else {
            result = "用户没有找见！！！";
        }

        // 记录日志
        UserQueryLog log = UserQueryLog.builder()
                .userId(userId)
                .query(query)
                .timestamp(LocalDateTime.now())
                .serviceName("UserService")
                .methodName("queryUserInfo")
                .success(success)
                .message(success ? "成功" : "用户未找见")
                .build();

        sendUserQueryLog(log);

        return result;
    }
}